import 'dart:math' as math;

import 'package:campus_vision/models/device/channel.dart';
import 'package:campus_vision/models/player/player_count.dart';
import 'package:campus_vision/providers/video_player_count_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers/device_providers.dart';
import '../providers/multi_video_player_provider.dart';
import 'player/playback_control_bar.dart';
import 'player/video_player_widget.dart';

class VideoWindowLayout extends ConsumerWidget {
  final Function(int) onVideoTap;
  final Function(int) onRefresh;

  const VideoWindowLayout({
    super.key,
    required this.onVideoTap,
    required this.onRefresh,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 获取网格尺寸
    final playerCount = ref.watch(videoPlayerCountProvider);
    debugPrint("[player] create videoWindow");
    // 根据不同的显示模式决定布局
    return Container(
      color: Colors.black,
      child: Stack(
        fit: StackFit.expand,
        children: [
          playerCount == PlayerCount.single
              ? _SinglePlayerContainer()
              : _GridPlayerContainer(),
          _playerControllerPanel(),
        ],
      ),
    );
  }

  Widget _playerControllerPanel() {
    return const Positioned(
      left: 0,
      right: 0,
      bottom: 0,
      child: PlaybackControlBar(),
    );
  }
}

class _SinglePlayerContainer extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final deviceId = ref.watch(
      multiVideoPlayerProvider.select((state) => state.value?.currentDeviceId),
    );
    if (deviceId == null) return const SizedBox();
    final channelId = ref
        .watch(
          multiVideoPlayerProvider
              .select((state) => state.value?.currentChannelIds),
        )
        ?.first;
    final channelList = ref.read(channelListProvider(deviceId)).value;
    if (channelList == null || channelList.isEmpty) return const SizedBox();
    var channel = channelList.first;
    if (channelId != null) {
      final tempChannel = channelList.firstWhere(
        (e) => e.id == channelId,
        orElse: () => const Channel(),
      );
      if (tempChannel.id != null) channel = tempChannel;
    }
    debugPrint("[player] create single Container");
    return VideoPlayerWidget(deviceId: deviceId, channel: channel);
  }
}

class _GridPlayerContainer extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 计算实际显示的控制器数量
    final deviceId = ref.watch(
      multiVideoPlayerProvider.select((state) => state.value?.currentDeviceId),
    );
    if (deviceId == null) return const SizedBox();
    final channelList = ref.read(channelListProvider(deviceId)).value;
    if (channelList == null || channelList.isEmpty) return const SizedBox();
    final channelIdList =
        ref.read(multiVideoPlayerProvider).value!.currentChannelIds;
    final playerCount = ref.read(videoPlayerCountProvider);
    final displayCount = playerCount.maxVideoCount;
    debugPrint("[player] create Grid Container ${channelIdList.length}");

    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: math.min(channelIdList.length, displayCount),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: playerCount.column,
        childAspectRatio: 4.0 / 3.0, // 所有窗口都使用4:3比例
        crossAxisSpacing: 1,
        mainAxisSpacing: 1,
      ),
      itemBuilder: (context, index) {
        final channelId = channelIdList[index];
        final tempChannel = channelList.firstWhere(
          (e) => e.id == channelId,
          orElse: () => const Channel(),
        );
        if (tempChannel.id != null) {
          return VideoPlayerWidget(deviceId: deviceId, channel: tempChannel);
        } else {
          return Container(color: Colors.black);
        }
      },
    );
  }
}
